package chuangyi.com.org.DOMIHome.Utils;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by zxh on 16/11/12.
 */

public class Utils {
    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            // 有存储的SDCard
            return true;
        } else {
            return false;
        }
    }

    public static boolean isContain(View view, float x, float y) {
        int[] point = new int[2];
        view.getLocationOnScreen(point);

        if (x >= point[0] && x <= (point[0] + view.getWidth()) && y >= point[1] && y <= (point[1] + view.getHeight())) {
            return true;
        }
        return false;
    }

    public static String getMd5ByFile(File file) throws FileNotFoundException {
        String value = null;
        FileInputStream in = new FileInputStream(file);
        try {
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            Log.e("DOMIHome.Utils", e.getMessage(), e);
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    Log.e("DOMIHome.Utils", e.getMessage(), e);
                }
            }
        }
        return value;
    }

    public static Integer getIntegerValue(Object value) {
        if (value == null)
            return null;
        try {
            String val = value.toString();
            return Integer.valueOf(val);
        } catch (Exception ex) {
            return null;
        }
    }

    public static int getIntValue(Object value) {
        if (value == null)
            return 0;
        try {
            String val = value.toString();
            return Integer.valueOf(val);
        } catch (Exception ex) {
            return 0;
        }
    }

    public static double getDoubleValue(Object value) {
        if (value == null)
            return 0;
        try {
            String val = value.toString();
            return Double.valueOf(val);
        } catch (Exception ex) {
            return 0;
        }
    }

    public static boolean getBooleanValue(Object value) {
        if (value == null) {
            return false;
        } else {
            String val = value.toString();
            if (val.equals("0") || val.equals("")) {
                return false;
            } else {
                return true;
            }
        }
    }

    public static Long getLongValue(Object value) {
        if (value == null)
            return 0l;
        try {
            return Long.valueOf(value.toString());
        } catch (Exception ex) {
            return 0l;
        }
    }

    public static Date getDateFromTimestamp(Object value) {
        if (value == null)
            return null;
        Long val = getLongValue(value);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(val * 1000);
        return calendar.getTime();
    }

    public static Date getDateFromFormat(Object value, String format) {
        if (value == null || format == null || "".equals(format))
            return null;
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        try {
            return dateFormat.parse(value.toString());
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * dpתpx
     */
    public static int dip2px(Context ctx, float dpValue) {
        final float scale = ctx.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * pxתdp
     */
    public static int px2dip(Context ctx, float pxValue) {
        final float scale = ctx.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static String getPathByUri(Uri imageUri, Context context) {
        if (context == null || imageUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri))
                return imageUri.getLastPathSegment();
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static File getFileByUri(Uri uri, Context context) {
        String path = getPathByUri(uri, context);
        if (path != null && "".equals(path) == false) {
            return new File(path);
        }
        return null;
    }

    public static String getFileExtension(String fileName) {
        if ("".equals(fileName) || fileName == null) {
            return "";
        }
        int index = fileName.lastIndexOf(".");
        if (index >= 0) {
            return fileName.substring(index + 1);
        }
        return "";
    }

    public static String getFileName(String url) {
        if ("".equals(url) || url == null) {
            return "";
        }
        int index = url.lastIndexOf("/");
        if (index >= 0) {
            return url.substring(index + 1);
        }
        return "";
    }

    public static boolean isNullOrEmpty(String str) {
        return (str == null || "".equals(str));
    }
}
//    public static String getPathByUri(Uri uri, Context context) {
//        if (null == uri) {
//            return null;
//        }
//        final String scheme = uri.getScheme();
//        String data = null;
//        if (scheme == null)
//            data = uri.getPath();
//        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
//            data = uri.getPath();
//        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
//            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
//            if (null != cursor) {
//                if (cursor.moveToFirst()) {
//                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
//                    if (index > -1) {
//                        data = cursor.getString(index);
//                    }
//                }
//                cursor.close();
//            }
//        }
//        return data;
//    }

//        String path = null;
//        if ("file".equals(uri.getScheme())) {
//            path = uri.getEncodedPath();
//            if (path != null) {
//                path = Uri.decode(path);
//                ContentResolver cr = context.getContentResolver();
//                StringBuffer buff = new StringBuffer();
//                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
//                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA }, buff.toString(), null, null);
//                int index = 0;
//                int dataIdx = 0;
//                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
//                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
//                    index = cur.getInt(index);
//                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
//                    path = cur.getString(dataIdx);
//                }
//                cur.close();
//                if (index == 0) {
//                } else {
//                    Uri u = Uri.parse("content://media/external/images/media/" + index);
//                    System.out.println("temp uri is :" + u);
//                }
//            }
//            return path;
//        } else if ("content".equals(uri.getScheme())) {
//            // 4.2.2以后
//            String[] proj = { MediaStore.Images.Media.DATA };
//            Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
//            if (cursor.moveToFirst()) {
//                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//                path = cursor.getString(columnIndex);
//            }
//            cursor.close();
//
//            return path;
//        } else {
//            Log.i("DOMI HOME", "Uri Scheme:" + uri.getScheme());
//        }
//        return null;
